import React,{Component} from 'react';
import { connect } from 'react-redux';
import { Card,Button,Input,Table,message,Select,Modal,Space} from 'antd';
import { PlusCircleOutlined,ExclamationCircleOutlined,SearchOutlined } from '@ant-design/icons';
import {reqDeleteContent,reqSearchContent,reqUpdateContentStatus,reqContentList,reqSearchByCourseId,reqUserList,reqAddRelation} from '../../../api';
import { saveContentListAction} from '../../../redux/action_creators/course_action';
import { saveStudentAction } from '../../../redux/action_creators/user_action';
import { saveRelationListAction} from '../../../redux/action_creators/course_action';
import {PAGE_SIZE,} from '../../../config';
import dayjs from 'dayjs';

const { Option } = Select;

@connect(
    state=>({
        course:state.course,
        userList:state.userList
    }),{
        saveContentList:saveContentListAction,
        saveStudentList:saveStudentAction,
        saveRelationList:saveRelationListAction
    }
)
class Content extends Component {
    state={
        contentList:[],//用户列表
        roleList:[],//角色列表
        isLoading:true, //table是否显示加载动画
        id:'',
        keyWord:'', //搜索关键词
        searchType:'courseName',//默认搜索方式按名称搜索
        isVisible:false,
        isAddVisible:false,
        studentCourseList:[],
        userList:[],
        teacherId:'',
        courseId:''
    }
    componentDidMount(){
        const { contentList } = this.props.course;
        if(contentList.length>0){
            // console.log(studentList);
            this.setState({
                contentList,
                isLoading:false,
            })
        }else{
            this.getTeacherList()
        }
    }

    // 获取课程列表
    getTeacherList = async () => {
        let result = await reqContentList()
        const { code,data,msg} = result
        // console.log(result);
       if(code === 200){
            this.setState({
                contentList:data,
                isLoading:false,
            })
            //   把课程列表保存到redux中
              this.props.saveContentList(data)
            //   数据为空时，显示提示信息
              if(data.length===0) message.success(msg,1)  
        }else{
            message.error(msg,1)      
        } 
    }

    // 删除课程信息
    deleteContent =  (id) => {
        let{ getDelete } = this
        Modal.confirm({
            icon: <ExclamationCircleOutlined/>,
            title:'删除课程',
            content:'你确定要删除课程信息吗？',
            okText:'确定',
            cancelText:'取消',
            onOk(){
                getDelete(id)
            },
            onCancel() {
                console.log('取消');
            },
        });
    }
    // 删除课程信息
    getDelete = async (id) =>{
        let  result = await reqDeleteContent(id)
        console.log(id);
        const { code,msg} = result
        if(code === 200){
            message.success('删除课程成功！',1)
            let contentList = [...this.state.contentList]
            let contentIndex;
            contentList.forEach((item,index)=> {
                if(item.id === id) contentIndex=index
            });
            contentList.splice(contentIndex,1)
            this.setState({contentList})
            this.props.saveContentList(contentList)
        }else{
            message.error(msg,1)
        }
    }
    // 根据搜索类型搜索
    searchTeacherType=  () => {
        const {keyWord} = this.state;
        const {contentList } = this.props.course;
        if(keyWord.length>0){
            this.searchContentList()
        }else{
            this.setState({
                contentList,
                isLoading:false,
            })
        }
    }
    // 搜索课程信息列表
    searchContentList = async () => {
        const {searchType,keyWord} = this.state
        let result = await reqSearchContent(searchType,keyWord)
        const { code,data,msg} = result
       if(code === 200){
           //   数据为空时，显示提示信息
           if(data.length===0) message.success(msg,1)  
            this.setState({
                contentList:data,
                isLoading:false,
            })
              // 把商品列表保存到redux中
            //   this.props.saveProductList(data.list)
        }else if(code === 404){
            this.props.history.push(`/admin/error`)
        }else{
            message.error(msg,1)      
        } 
    }
      // 修改课程状态
      updateProductStatus= async (id,courseStatus) => {
        let contentList = [...this.state.contentList]
        if(courseStatus === 1) courseStatus = 0
        else courseStatus = 1
        let result =await reqUpdateContentStatus(id,courseStatus)
        const { code,msg} = result
        if(code === 200){
            message.success('课程状态修改成功',1)
            contentList = contentList.map((item)=>{
                if(item.id === id)     item.courseStatus = courseStatus
                return item;
            })
            this.setState({contentList})
            this.props.saveContentList(contentList)
        }else{
            message.error(msg,1)
        }
    }
     // 展示弹窗
     showModelCourse=async(courseId)=>{
        console.log(courseId);
        let result = await reqSearchByCourseId(courseId)
        const { code,data,msg} = result
        console.log(result);
       if(code === 200){
        if(data.length===0)  message.success(msg,1)
            this.setState({
                studentCourseList:data,
                isVisible:true,
            })
        }else{
            message.error(msg,1)      
        } 
    }
    showModelAddStudent=(course)=>{
        const {teacherId,id} = course
        this.setState({isAddVisible:true,teacherId,courseId:id})
        const {studentList } = this.props.userList;
        if(studentList.length>0){
            // console.log(studentList);
            this.setState({
                userList:studentList,
                isLoading:false,
            })
        }else{
            this.getUserList()
        }
    }
    addStudentCourse= async ()=>{
        const {teacherId,courseId} = this.state
        const userId =this.userId
        if(!userId){
            message.error("请先选择需要添加的学员",1)
            return ;
        }
        console.log(userId,teacherId,courseId);
        const relation ={userId,teacherId,courseId}
        let result = await reqAddRelation(relation)
        const { code,data,msg} = result
        if(code === 200){
            message.success(msg,1)
            //   把用户列表保存到redux中
            this.props.saveRelationList(data)
            this.setState({isAddVisible:false})
        }else{
            message.error(msg,1)      
        } 
    }
    // 获取用户列表
    getUserList = async () => {
        let result = await reqUserList()
        const { code,data,msg} = result
        // console.log(result);
        if(code === 200){
            if(data.length===0)  message.success(msg,1)
            this.setState({
            userList:data,
        })
            //   把用户列表保存到redux中
                this.props.saveStudentList(data)
        }else{
            message.error(msg,1)      
        } 
    }
    render(){
        const  {contentList,searchType,isVisible,isAddVisible,studentCourseList,userList} = this.state
          const columns = [
            {title: '课程编号',
                dataIndex: 'courseNum',
                key: 'id',
            },
            {title: '课程名称',
              dataIndex: 'courseName',
              key: 'id',
            },
            {title: '授课讲师',
              dataIndex: 'username',
              key: 'id',
            },
            {title: '授课地点',
                dataIndex: 'courseRoom',
                key: 'id', 
            },
            {title: '课程日期',
                dataIndex: 'courseDate',
                key: 'id', 
                render:(courseDate)=>{return courseDate? courseDate.replace(/,/g, " 至 "):''}
            },
            {title: '课程周期',
              dataIndex: 'courseWeek',
              key: 'id',
            },
            {title: '课程时间',
                dataIndex: 'courseTime',
                key: 'id',
                render:(courseTime)=>{ return courseTime ? courseTime.replace(/,/g, " 至 ") : ''}
            },
            {title: '课程价格（元）',
              align:'center',
              dataIndex: 'price',
              key: 'id',
            },
            {
                title: '状态',
                // dataIndex: 'status',
                key: 'id',
                align:'center',
                width:'10%',
                render:(item)=>{
                    return(
                        <div>
                            <Button 
                                type={item.courseStatus=== 1?"danger":"primary"}
                                onClick={()=>this.updateProductStatus(item.id,item.courseStatus)}
                            >
                                {item.courseStatus=== 1 ? '下架':'上架'}
                            </Button><br/>
                            <span>{item.courseStatus=== 1 ? '在售':'停售'}</span>
                        </div>
                    )
                }
            },
            {title: '操作',
                key: 'id',
                align:'center',
                render:(item)=>{
                    return(
                        <div>
                             <Button type="link" onClick={()=>{this.showModelCourse(item.id)}}>报名情况</Button>
                             <Button type="link" onClick={()=>{this.showModelAddStudent(item)}}>添加学员</Button>
                             <Button type="link" onClick={()=>{this.props.history.push(`/training/admin/course/content/detail/${item.id}`)}}>详情</Button>
                             <Button type="link" onClick={()=>{this.props.history.push({ pathname:`/training/admin/course/content/update/${item.id}`,state:{contentItem:item} })}}>修改</Button>
                            <Button type="link" onClick={()=>{this.deleteContent(item.id)}}>删除</Button>
                        </div>
                    )
                }
            },
          ];
          const columnCourse = [
            {
                title: '姓名',
                dataIndex: 'studentName',
                key: 'id',
              },
              {
                  title: '学号',
                  dataIndex: 'studentNum',
                  key: 'id',
                },
              {
                title: '邮箱',
                dataIndex: 'email',
                key: 'id',
              },
              {
                  title: '生日',
                  dataIndex: 'birthday',
                  key: 'id',
                  render:time=>dayjs(time).format('YYYY年MM月DD日')
              },
              {
                title: '电话',
                dataIndex: 'phone',
                key: 'id',
              },
              {
                  title: '报名时间',
                  dataIndex: 'createTime',
                  key: 'id',
                  render:time=>dayjs(time).format('YYYY年MM月DD日  HH:mm:ss')
              },
              {
                  title: '性别',
                  dataIndex: 'sex',
                  key: 'id',
              },
          ];
        return (
            <div>
                <Card
                    title={
                        <Space size="small">
                        <Select 
                            defaultValue={searchType} 
                            style={{ width: 150 }} 
                            onChange={(value)=>{this.setState({searchType:value})}}
                        >
                            <Option key="1" value="courseName">按课程名字搜索</Option>
                            <Option key="2" value="courseNum">按课程编号搜索</Option>
                            {/* <Option key="3" value="username">按授课老师搜索</Option>
                            <Option key="4" value="userNum">按讲师工号搜索</Option> */}
                        </Select>
                        <Input 
                         style={{ width: 220 }} 
                            placeholder="请输入关键字" 
                            className="selectInput" 
                            allowClear
                            onChange={(event)=>{this.setState({keyWord:event.target.value})}}
                        />
                        <Button
                            type="primary"
                            onClick={this.searchTeacherType}
                        >
                            <SearchOutlined />搜索
                        </Button>
                   </Space>
                     } 
                     extra={
                        <Button type="primary"  onClick={()=>{this.props.history.push({ pathname:`/training/admin/course/content/update`,state:{contentItem:[]} })}}>
                        <PlusCircleOutlined/>添加课程信息</Button>
                    }
                >
                    <Table 
                        dataSource={contentList} 
                        columns={columns}
                        bordered
                        rowKey='id'
                        pagination={{
                            pageSize:PAGE_SIZE,
                        }}
                        loading={this.state.isLoading} 
                    />
                </Card>
                <Modal
                    title="报名学员"
                    visible={isVisible}
                    onOk={()=>this.setState({isVisible:false})}
                    onCancel={()=>this.setState({isVisible:false})}
                    footer={null}
                    maskClosable={false}
                    width={1200}
                    >
                     <Table 
                        dataSource={studentCourseList} 
                        columns={columnCourse}
                        bordered
                        rowKey='id'
                        pagination={{
                            pageSize:PAGE_SIZE,
                        }}
                        loading={this.state.isLoading} 
                    />
                    </Modal>
                    <Modal
                    title="报名课程"
                    visible={isAddVisible}
                    onOk={this.addStudentCourse}
                    onCancel={()=>this.setState({isAddVisible:false})}
                    cancelText={'取消'}
                    okText={'确定'}
                    // footer={null}
                    maskClosable={false}
                    width={300}
                    >
                        <span>学员：</span><Select placeholder="请选择需要添加的学员" onChange={(value)=>this.userId=value}>
                        {userList.map((item)=>{
                           
                            return  <Option key={item.id} value={item.id}>{item.username}&nbsp;&nbsp;&nbsp;&nbsp;{item.userNum}</Option>
                        })}
                        </Select>
                    </Modal>
            </div>
        );
    }
}
export default Content;